import { Component, OnInit } from '@angular/core';
import { FormArray, FormControl, FormGroup, Validators } from '@angular/forms';

@Component({
  selector: 'app-form2',
  templateUrl: './form2.component.html',
  styleUrls: ['./form2.component.css']
})
export class Form2Component implements OnInit {
  contactForm: FormGroup = new FormGroup({
    info: new FormGroup({
      username: new FormControl('fujun'),
      age: new FormControl(18),
    }),
    hobbies: new FormArray([], [
      Validators.required,
      Validators.minLength(2),
      Validators.maxLength(5),
    ])
  })

  get hobbies() {
    return this.contactForm.get('hobbies') as FormArray
  }

  createHobby() {
    const hobbyGroup = new FormGroup({
      hobby: new FormControl('', [
        Validators.required,
        Validators.minLength(2),
        Validators.maxLength(5),
      ])
    })
    this.hobbies.push(hobbyGroup)
    console.log(this.hobbies)
  }

  removeHobby(i: number) {
    this.hobbies.removeAt(i)
  }

  constructor() { }

  ngOnInit(): void {
    this.createHobby()
  }

  handleSubmit() {
    console.log(this.contactForm.value)
  }

}
